package com.yuteng.security.config.handler;

import com.alibaba.fastjson.JSON;

import com.yuteng.security.config.JwtTokenUtil;
import com.yuteng.security.config.RedisUtils;
import com.yuteng.security.entity.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
登出成功
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    JwtTokenUtil jwtTokenUtil;
    @Resource
    RedisUtils redisUtils;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String accessToken = httpServletRequest.getHeader("Authorization");
        if (accessToken != null) {
            accessToken = accessToken.replace("Bearer ", "");
        }
        String usernameFromToken = jwtTokenUtil.getUsernameFromToken(accessToken);
        if (usernameFromToken==null){
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(new Result<String>(false,4000,"登出失败，请重新登录")));
        }
        else {
            redisUtils.remove(usernameFromToken);
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(new Result<String>(true,5000,"登出成功")));
        }
    }
}
